package com.ayoka.parenting.widget;

import android.os.Handler;
import android.os.Looper;

import java.util.Observable;


public class MyCountDownTimer extends Observable {

    private volatile static MyCountDownTimer instance;

    private Handler handler;

    private boolean isRunning;

    private MyCountDownTimer() {
        handler = new Handler(Looper.getMainLooper());
    }

    public static MyCountDownTimer getInstance() {
        if (instance == null) {
            synchronized (MyCountDownTimer.class) {
                if (instance == null) {
                    instance = new MyCountDownTimer();
                }
            }
        }
        return instance;
    }

    /**
     * 开始
     */
    public void start() {
        if (handler != null && !isRunning) {
            handler.post(task);
            isRunning = true;
        }
    }

    /**
     * 开始
     */
    public void stop() {
        if (handler != null) {
            handler.removeCallbacks(task);
            isRunning = false;
        }
    }

    /**
     * 清理
     */
    public void destroy() {
        stop();
        deleteObservers();
        instance = null;
    }

    private Runnable task = new Runnable() {
        @Override
        public void run() {
            setChanged();
            notifyObservers(System.currentTimeMillis());
            handler.postDelayed(this, 1000);
        }
    };
}